package login

import (
	"context"
	"fmt"
	"time"

	"ruoyi_zero/domain/system"
	"ruoyi_zero/internal/svc"
	"ruoyi_zero/internal/types"
	"ruoyi_zero/utils"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	// todo: add your logic here and delete this line
	resp = new(types.LoginResponse)

	user := system.SysUser{}

	//user.UserName = "zhang san"
	//user.UserId = 1
	//user.DeptId = 100
	l.svcCtx.DB.Where("user_name = ?", req.Username).Find(&user)
	fmt.Printf("%v", user)

	// if user.Password != utils.MD5V(req.Password) {

	// }
	now := time.Now().Unix()

	jwtToken, err := l.getJwtToken(l.svcCtx.Config.Auth.AccessSecret, now, l.svcCtx.Config.Auth.AccessExpire, user.UserId)
	if err != nil {
		return nil, utils.NewCodeError(201, fmt.Sprintf("[授权错误]%v", err), "")
	}
	//data := make(map[string]interface{})
	//data["token"] = jwtToken
	// data["user"] = user
	resp.Token = jwtToken
	resp.Code = 200
	resp.Msg = "ok"
	return
}

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
func (l *LoginLogic) getJwtToken(secretKey string, iat, seconds int64, payload int) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	//claims["userId"] = userInfo.UserId
	//claims["userName"] = userInfo.UserName
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
